package services

import (
	"fmt"
	"github.com/goravel/framework/contracts/database/orm"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/errors"
	"github.com/goravel/framework/facades"
	"github.com/jinzhu/copier"
	"goravel/app/models"
	"goravel/app/types"
	"math"
)

type DBService struct {
	Ctx http.Context
}

func NewDBService() *DBService {
	return &DBService{}
}

func (r *DBService) ListPage(ctx http.Context, dest any, query orm.Query, target any) (any, types.Meta, error) {
	pageSize := ctx.Request().QueryInt("page_size", 10)
	currentPage := ctx.Request().QueryInt("current_page", 1)
	total := int64(0)
	meta := types.Meta{}
	var err error
	err = query.Paginate(currentPage, pageSize, dest, &total)
	if err != nil {
		return nil, meta, err
	}
	totalPage := int(math.Ceil(float64(total) / float64(pageSize)))
	meta.Page = currentPage
	meta.PageSize = pageSize
	meta.Total = int(total)
	meta.TotalPage = totalPage

	if total == 0 {
		return dest, meta, nil
	}
	if target == nil {
		return dest, meta, nil
	}
	err = copier.Copy(target, dest)
	if err != nil {
		return nil, meta, err
	}
	return target, meta, nil
}

func (r *DBService) GetById(model any, req any, id int64) (any, error) {
	var err error
	err = facades.Orm().Query().FindOrFail(model, id)
	if err != nil {
		return nil, errors.New("无相关数据")
	}
	if req == nil {
		return model, nil
	}
	err = copier.Copy(req, model)
	if err != nil {
		return nil, errors.New("copier错误")
	}
	return req, nil
}

// Create 创建,model,req必须是指针
func (r *DBService) Create(model any, req any) error {
	var err error
	if req != nil {
		err = copier.Copy(model, req)
		if err != nil {
			return errors.New("copier错误")
		}
	}
	err = facades.Orm().Query().Create(model)
	if err != nil {
		return errors.New("数据库新建错误")
	}
	return nil
}

// Update 更新,model,req必须是指针
func (r *DBService) Update(model any, req any, id int64) error {
	var err error
	err = facades.Orm().Query().FindOrFail(&model, id)
	if err != nil {
		return errors.New("无相关数据")
	}
	fmt.Println(model.(*models.SysRole).Name)
	fmt.Println(req.(*types.RoleUpdateReq).Name)
	if req != nil {
		fmt.Println("copier1")
		err = copier.CopyWithOption(model, req, copier.Option{IgnoreEmpty: true})
		if err != nil {
			return errors.New("copier错误")
		}
		fmt.Println("copier2")
	}
	err = facades.Orm().Query().Save(model)
	if err != nil {
		return errors.New("数据库更新错误")
	}
	return nil
}

// Delete 删除,dao必须是指针
func (r *DBService) Delete(dao any, id int64) error {
	var err error
	err = facades.Orm().Query().FindOrFail(dao, id)
	fmt.Println("109", id)
	if err != nil {
		return errors.New("无相关数据")
	}
	_, err = facades.Orm().Query().Delete(dao)
	fmt.Println("114", id)
	if err != nil {
		return errors.New("数据库删除错误")
	}
	return nil
}
